package com.maximus.server.nio.normal;

import com.maximus.server.nio.ReadAndWrite;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

//普通nio
public class NioServer {
    private static final Logger logger = LogManager.getLogger(NioServer.class);
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;

    public NioServer(int port) throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void listen() throws IOException {
        while (true) {
            int select = selector.select();
            if (select > 0) {
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectionKeySet.iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        handleMsg(selectionKey);
                    }
                }
                // 移除key，以免重复使用
                keyIterator.remove();
            }
        }
    }

    private void handleMsg(SelectionKey selectionKey) {
        SocketChannel channel = null;
        try
        {
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            ReadAndWrite.readAndWrite(channel, byteBuffer);
        }
        catch (IOException e) {
            try {
                logger.info(channel.getRemoteAddress() + "离线了...");
                selectionKey.cancel();
                channel.close();
            }
            catch (IOException ioException) {
                logger.error(ioException);
            }
        }
    }
}
